package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;


@AllArgsConstructor
public class SimpleRedisLock implements Ilock {


    private String name;
    private static final String KEY_PREFIX="Redislock:";
    private StringRedisTemplate stringRedisTemplate;
    private static final String ID_PREFIX=UUID.randomUUID().toString(true)+ "-";

    //加载unlock-lua脚本
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;
    static {
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }

    /**
     * 生成分布式锁  ---- 解决一人一单的多服务节点并发问题
     * @param timeoutSec 锁持有的超时时间，过期后自动释放
     * @return
     */
    @Override
    public boolean tryLock(long timeoutSec) {
        Thread currentID = Thread.currentThread();
        // 获取线程标示（用来解决是否删的不是自己的锁的问题 必须要删除自己的锁！）
        String value=ID_PREFIX+currentID.getId();
        Boolean Boolean = stringRedisTemplate.opsForValue()
                .setIfAbsent(KEY_PREFIX + name, value, timeoutSec, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(Boolean);
    }

    //基于Lua脚本释放锁
    @Override
    public void unlock() {
        // 调用lua脚本
        stringRedisTemplate.execute(
                UNLOCK_SCRIPT,
                Collections.singletonList(KEY_PREFIX + name),
                ID_PREFIX + Thread.currentThread().getId());
    }


/*    //释放锁
    @Override
    public void unlock() {

        //删除锁之前先判断是否是自己当前线程的锁（根据ID_PREFIX+currentID.getId()来判断）
        String value = stringRedisTemplate.opsForValue().get(KEY_PREFIX + name);
        if (value.equals(ID_PREFIX+Thread.currentThread().getId())){
            stringRedisTemplate.delete(KEY_PREFIX + name);
        }
    }*/
}
